package com.ecreditpal.audio.controller;

import com.ecreditpal.audio.model.Result;
import com.ecreditpal.audio.model.ServerInfo;
import com.ecreditpal.audio.platform.PlatformConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lifeng
 * @version 1.0 on 2018/7/4.
 * 用于发现可用的服务
 */
@RestController
@RequestMapping("server")
public class DispatchController {

    @Autowired
    DiscoveryClient client;

    @Autowired
    LoadBalancerClient loadBalancerClient;

    @Autowired
    PlatformConfig platformConfig;

    @RequestMapping("available")
    public Result<List<ServerInfo>> getAvailableServer() {
       List<ServiceInstance> list =  client.getInstances("SPEECH-SEG-SERVICE");

       List<ServerInfo> serverInfos = new ArrayList<>();
        for (ServiceInstance serviceInstance : list) {
           String port = serviceInstance.getMetadata().get("nettyServer");
           String host = serviceInstance.getHost();
           ServerInfo serverInfo = new ServerInfo(host,port);
            serverInfos.add(serverInfo);
        }
        return Result.wrapSuccessfulResult(serverInfos);
    }


    @RequestMapping("ribbon/available")
    public Result<ServerInfo> getAvailableServerRibbon() {
       ServiceInstance serviceInstance =  loadBalancerClient.choose("audio");
        String port = serviceInstance.getMetadata().get("nettyServer");
        String host = serviceInstance.getHost();
        ServerInfo serverInfo = new ServerInfo(host,port);
        return Result.wrapSuccessfulResult(serverInfo);
    }
}
